package com.hmdp.common.lock.impl;

import cn.hutool.core.lang.UUID;
import com.hmdp.common.lock.ILock;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 公众号/B站：是叶十三
 * @Date: 2022/11/18
 * @Description: com.hmdp.common.lock.impl
 * @version: 1.0
 */
public class LuaAndUUIDRedisLock implements ILock {

    private RedisTemplate redisTemplate;
    private String name;

    private static final String KEY_PREFIX = "lock:";


    // 引入uuid 防止锁被误删
    // true 去掉uuid里的横线
    private static final String UUID_PREFIX = UUID.randomUUID().toString(true) + "-";

    // lua脚本 提前加载
    private static DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public LuaAndUUIDRedisLock(String name, RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //  获取当前线程标识
        String threadId = Thread.currentThread().getId() + UUID_PREFIX;
        Boolean success = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name , threadId + "", timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        // 获取redis锁种的标识
//        String redisKey = KEY_PREFIX + name;
        //  获取线程标识
//        String threadId = UUID_PREFIX + Thread.currentThread().getId();
        redisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                UUID_PREFIX + Thread.currentThread().getId()
        );
    }
}
